import { addUnit } from '@/app/style'

// 转驼峰命名，用 - 连接
function toLowercaseSeparator(key) {
  return key.replace(/([A-Z])/g, '-$1').toLowerCase()
}

export function getStyleStr(style) {
  return Object.keys(style)
    .map((key) => `${toLowercaseSeparator(key)}: ${style[key]};`)
    .join(' ')
}

export function getPixelRatio() {
  return window.devicePixelRatio || 1
}

export function getMarkSize(ctx, props, FontGap) {
  let defaultWidth = 120
  let defaultHeight = 64
  const p = props
  const content = p.content
  const width = p.width
  const height = p.height
  const fontSize = p.fontSize
  if (!p.image && ctx.measureText) {
    ctx.font = `${addUnit(Number(fontSize))} ${p.fontFamily}`
    const contents = Array.isArray(content) ? content : [content]
    const widths = contents.map((item) => ctx.measureText(item).width)
    defaultWidth = Math.ceil(Math.max(...widths))
    defaultHeight =
      Number(fontSize) * contents.length + (contents.length - 1) * FontGap
  }
  return [width ?? defaultWidth, height ?? defaultHeight]
}

export function fillTexts(
  ctx,
  drawX,
  drawY,
  drawWidth,
  drawHeight,
  props,
  FontGap,
) {
  const p = props
  console.log(p.fontWeight)

  const ratio = getPixelRatio()
  const content = p.content
  const fontSize = p.fontSize
  const fontWeight = p.fontWeight
  const fontFamily = p.fontFamily
  const fontStyle = p.fontStyle
  const color = p.color
  const mergedFontSize = Number(fontSize) * ratio
  ctx.font = `${fontStyle} normal ${fontWeight} ${mergedFontSize}px/${drawHeight}px ${fontFamily}`
  ctx.fillStyle = color
  ctx.textAlign = 'center'
  ctx.textBaseline = 'top'
  ctx.translate(drawWidth / 2, 0)
  const contents = Array.isArray(content) ? content : [content]
  contents?.forEach((item, index) => {
    ctx.fillText(
      item ?? '',
      drawX,
      drawY + index * (mergedFontSize + FontGap * ratio),
    )
  })
}

export function rotateWatermark(ctx, rotateX, rotateY, rotate) {
  ctx.translate(rotateX, rotateY)
  ctx.rotate((Math.PI / 180) * Number(rotate))
  ctx.translate(-rotateX, -rotateY)
}

export function isRendering(mutation, watermarkElement) {
  let flag = false
  // 无水印节点/水印节点被移除
  if (mutation.removedNodes.length) {
    flag = Array.from(mutation.removedNodes).some(
      (node) => node === watermarkElement,
    )
  }
  // 水印dom属性值已修改
  if (mutation.type === 'attributes' && mutation.target === watermarkElement) {
    flag = true
  }
  return flag
}
